#!/bin/bash
# 用途：计算一个小时内进程的CPU占用情况

SECS=60                     #监控时长，单位为秒
UNIT_TIME=60                  #取样时间间隔，单位为秒

STEPS=$(( $SECS / $UNIT_TIME ))

echo "Watching CPU usage..." ;

for((i = 0; i < STEPS; i++))
do
	ps -eo comm,pcpu | tail -n +2 >> /tmp/cpu_usage.$$
	sleep $UNIT_TIME
done

echo
echo CPU eaters:
echo

cat /tmp/cpu_usage.$$ | \
awk '
	{ process[$1] += $2; }
	END {
		for(i in process) {
			printf("%-20s %s", i, process[i] ;
		}
	}' 
| sort -nrk 2 | head

rm /tmp/cpu_usage.$$
